<template>
  <div class="contain">
    <seacrh></seacrh>

    <el-card>
      <div class="cartword">购物车</div>
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="150" />
        <!-- <el-table-column label="Date" width="320">
     <template #default="scope">{{ scope.row.date }}</template>
   </el-table-column> -->
        <el-table-column label="图片" width="320">
          <template #default="scope">
            <div style="position: relative">
              <!-- <el-image :preview-src-list='a(scope.row)' /> -->
              <img
                :src="a(scope.row)"
                class="cartimg"
                @click="store.dispatch('goproductsellpage', scope.row.id)"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column property="name" label="商品信息" width="380">
          <template #default="scope">
            <span
              @click="store.dispatch('goproductsellpage', scope.row.id)"
              class="productname"
            >
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          class="number"
          property="price"
          label="单价"
          width="280"
        />
        <el-table-column label="数量" width="180">
          <template #default="scope">
            <div style="position: relative">
              <!-- <el-image :preview-src-list='a(scope.row)' /> -->
              <el-input-number
                v-model="scope.row.num"
                :min="1"
                :max="10"
                @change="handleChange($event, scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column property="all" label="金额" width="220" /> -->
        <el-table-column fixed="right" label="Operations" width="320">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.$index, scope.row.id)"
            >
              Remove
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="cartbottom">
        <div>
          <el-checkbox v-model="checked1" label="全选" size="large" />
          <Span class="bottomitem">删除</Span>
          <span class="bottomitem" @click="insertstar()">移入收藏夹</span>
        </div>

        <div>
          <span class="bottomitem"
            >已选商品<span class="number">{{ selection.number }}</span
            >件</span
          >
          <span class="bottomitem"
            >合计:<span class="number">{{ selection.totalprice }}</span></span
          >
          <el-button type="danger" round @click="goaccounts()">结算</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>


<script setup>
import seacrh from "../../components/search/seacrh.vue";
import { onMounted, reactive, ref } from "vue";
import { ElTable } from "element-plus";
import {
  CartproductApi,
  updatecartnumApi,
  deleteproductincartApi,
  addloveApi,
} from "../../api/goods";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";

const store = useStore();

const multipleTableRef = ref();
const multipleSelection = ref([]);
const router = useRouter();
const route = useRoute();
const selection = reactive({
  number: 0,
  totalprice: 0,
});

const toggleSelection = (rows) => {
  rows.forEach((row) => {
    // TODO: improvement typing when refactor table
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    multipleTableRef.value.toggleRowSelection(tableData.value[row]);
  });
};
const a = (e) => {
  return `http://localhost:3001/${e.img}`;
};
const deleteRow = async (index, id) => {
  tableData.value.splice(index, 1);
  let data = await deleteproductincartApi(store.state.user.user_id, id);

  if (data.code == "001") {
    ElMessage({
      message: data.msg,
      type: "success",
    });
  } else ElMessage.error("删除失败！");
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;

  selection.number = multipleSelection.value.length;
  selection.totalprice = 0;
  multipleSelection.value.forEach((item) => {
    selection.totalprice = selection.totalprice + item.price * item.num;
  });
};
const getcartproduct = async () => {

  let data = await CartproductApi(store.state.user.user_id);

  data.shoppingCartData.forEach((ele) => {
    let tabledata = {
      img: "product_picture",
      name: "product_name",
      num: 0,
      price: 0,
      all: 0,
      id: "",
    };
    tabledata.img = ele.productImg;
    tabledata.name = ele.productName;
    tabledata.num = ele.num;
    tabledata.price = ele.price;
    tabledata.all = ele.price * ele.num;
    tabledata.id = ele.productID;
    tableData.value.push(tabledata);
  });
  if (route.query.product) {
    addselect();
  }
};
const handleChange = async (e, row) => {
  await updatecartnumApi(store.state.user.user_id, row.id, e);

  // multipleSelection.value.forEach((item)=>{
  //   if(item == row){

  //   }
  // })
  let res = multipleSelection.value.findIndex((item, index) => {
    //获取第一个满足大于18的索引
    return item == row;
  });
  if (res != -1) {
    selection.totalprice = 0;
    multipleSelection.value.forEach((item) => {
      selection.totalprice = selection.totalprice + item.price * item.num;
    });
  }
};
getcartproduct();
const tableData = ref([]);

const goaccounts = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage({
      type: "info",
      message: `还没有选购商品`,
    });
  } else {
    router.push({
      path: "/accounts",
      query: {
        order: JSON.stringify(multipleSelection.value),
        total: selection.totalprice,
      },
    });
  }
};

onMounted(() => {});

const addselect = () => {
  let arr = JSON.parse(route.query.product);
  let arrindex = [];

  tableData.value.forEach((item, index) => {
    arr.forEach((ele) => {
      if (item.id == ele.id) {
        arrindex.push(index);
      }
    });
  });

  toggleSelection(arrindex);
};

const insertstar = async () => {
  console.log(multipleSelection.value);
  multipleSelection.value.forEach(async (item) => {
    let data = await addloveApi(store.state.user.user_id, item.id);
    console.log(data);
    await deleteproductincartApi(store.state.user.user_id, item.id)
    //
     tableData.value = []
     getcartproduct();
      ElMessage({
      message: `移入成功`,
      type: "success",
    });

  
  });
};
</script>


 <style scoped>
.el-table {
  text-align: center;
}
.cartimg {
  width: 100px;
  height: 100px;
  margin: 50px 0;
}
.productname:hover {
  color: red;
}
.cartword {
  height: 50px;
  border-bottom: 1px solid #e3e4e5;
  margin: 20px;
}
.contain {
  background-color: #e3e4e5;
  margin: 20px 0;
}
.el-card {
  width: 90%;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}
.cartbottom {
  border-top: 1px solid #e3e4e5;
  display: flex;
  justify-content: space-between;
  height: 80px;
  line-height: 80px;
  padding: 0 20px;
}
.bottomitem {
  margin: 40px;
}
.number {
  font-size: 20px;
  margin: 0 5px;
  color: red;
}
</style>

